#include "ccw_adc.h"

volatile ccw_u16 g_adc_converted_value[ADC_CHANNEL_NUM];

void ccw_adc_init(void)
{
    ADC_InitTypeDef ADC_InitStructure;
    DMA_InitTypeDef DMA_InitStructure;
    
    // 1. 开启时钟
    RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1, ENABLE);
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1 | RCC_APB2Periph_GPIOA, ENABLE);
    
    // 2. 配置DMA
    DMA_DeInit(DMA1_Channel1);
    DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)&ADC1->DR;
    DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)g_adc_converted_value;
    DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralSRC;
    DMA_InitStructure.DMA_BufferSize = ADC_CHANNEL_NUM;
    DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
    DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
    DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord;
    DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_HalfWord;
    DMA_InitStructure.DMA_Mode = DMA_Mode_Circular;
    DMA_InitStructure.DMA_Priority = DMA_Priority_High;
    DMA_InitStructure.DMA_M2M = DMA_M2M_Disable;
    DMA_Init(DMA1_Channel1, &DMA_InitStructure);
    
    // 3. 使能DMA
    DMA_Cmd(DMA1_Channel1, ENABLE);
    
    // 4. 配置ADC时钟
    RCC_ADCCLKConfig(RCC_PCLK2_Div6);  // 72MHz/6 = 12MHz
    
    // 5. 配置ADC参数
    ADC_InitStructure.ADC_Mode = ADC_Mode_Independent;
    ADC_InitStructure.ADC_ScanConvMode = ENABLE;        // 扫描模式
    ADC_InitStructure.ADC_ContinuousConvMode = ENABLE; // 连续转换
    ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None;
    ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
    ADC_InitStructure.ADC_NbrOfChannel = ADC_CHANNEL_NUM;
    ADC_Init(ADC1, &ADC_InitStructure);
    
    // 6. 配置ADC规则通道
    // 通道0 (PA0) 采样时间55.5周期
    ADC_RegularChannelConfig(ADC1, ADC_Channel_0, 1, ADC_SampleTime_55Cycles5);
    // 通道1 (PA1) 采样时间55.5周期
    ADC_RegularChannelConfig(ADC1, ADC_Channel_1, 2, ADC_SampleTime_55Cycles5);
    
    // 7. 使能ADC DMA
    ADC_DMACmd(ADC1, ENABLE);
    
    // 8. 使能ADC
    ADC_Cmd(ADC1, ENABLE);
    
    // 9. ADC校准
    ADC_ResetCalibration(ADC1);
    while(ADC_GetResetCalibrationStatus(ADC1));
    
    ADC_StartCalibration(ADC1);
    while(ADC_GetCalibrationStatus(ADC1));
    
    // 10. 启动ADC转换
    ADC_SoftwareStartConvCmd(ADC1, ENABLE);
}

ccw_u16 ccw_adc_get_value(ccw_u8 channel)
{
    if(channel >= ADC_CHANNEL_NUM) {
        return 0;
    }
    return g_adc_converted_value[channel];
}

float ccw_adc_get_voltage(ccw_u8 channel)
{
    if(channel >= ADC_CHANNEL_NUM) {
        return 0;
    }
    return (float)g_adc_converted_value[channel] * 3.3f / 4096.0f;
}
